package com.tuyenmonkey.mkloader.type;

import com.tuyenmonkey.mkloader.model.Circle;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;

public class TwinFishesSpinner extends LoaderView {
  private Circle[] circles;
  private int numberOfCircle;
  private float[] rotates;
  private int delayTime;

  public TwinFishesSpinner() {
    numberOfCircle = 10;
    rotates = new float[numberOfCircle];
  }

  @Override public void initializeObjects() {
    final float size = Math.min(width, height);
    final float circleRadius = size / 10.0f;
    circles = new Circle[numberOfCircle];

    for (int i = 0; i < numberOfCircle / 2; i++) {
      circles[i] = new Circle();
      circles[i].setCenter(center.getPointX(), circleRadius);
      circles[i].setColor(color);
      circles[i].setRadius(circleRadius - circleRadius * i / 6);
    }

    for (int i = numberOfCircle / 2; i < numberOfCircle; i++) {
      circles[i] = new Circle();
      circles[i].setCenter(center.getPointX(), size - circleRadius);
      circles[i].setColor(color);
      circles[i].setRadius(circleRadius - circleRadius * (i - 5) / 6);
    }
  }

  @Override public void setUpAnimation() {
    for (int i = 0; i < numberOfCircle; i++) {
      final int index = i;
      AnimatorValue fadeAnimator = new AnimatorValue();
      fadeAnimator.setLoopedCount(AnimatorValue.INFINITE);
      fadeAnimator.setDuration(1800);
      delayTime = (index >= 5 ? index - 5 : index) * 100;
      fadeAnimator.setDelay(delayTime);
      fadeAnimator.setCurveType(Animator.CurveType.ACCELERATE);
      fadeAnimator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
        @Override
        public void onUpdate(AnimatorValue animatorValue, float v) {
          rotates[index] = v * 360;
          if (invalidateListener != null) {
            invalidateListener.reDraw();
          }
        }
      });

      fadeAnimator.start();
    }
  }

  @Override public void draw(Canvas canvas) {
    for (int i = 0; i < numberOfCircle; i++) {
      canvas.save();
      canvas.rotate(rotates[i], center.getPointX(), center.getPointY());
      circles[i].draw(canvas);
      canvas.restore();
    }
  }
}
